package com.powerunion.datacollection.web.struts;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.powerunion.datacollection.service.RoleManager;
import com.powerunion.datacollection.service.UsersRolesManager;
import com.powerunion.datacollection.transaction.Transaction;
import com.powerunion.datacollection.transaction.TransactionHelper;
import com.powerunion.util.log.LogHelper;

public class RoleAction extends DispatchAction {

	private static final Logger logger = LogHelper.getInstance().getLogger(RoleAction.class);
	private RoleManager roleManager = null;
	
	public RoleAction() {
		super();
		this.roleManager = new RoleManager();
	}
	
	public void finalize() throws Throwable {
		this.roleManager = null;
		super.finalize();
	}
	
	public ActionForward save (ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response)
	        throws Exception {
		
		String roleStr = request.getParameter("roleStr");
		String roleUsers = request.getParameter("roleUsers");
	  
		Transaction transaction = null;
		try {
			transaction = TransactionHelper.getTransaction();
			transaction.begin();
			logger.debug("角色信息定义:"+roleStr);
			
			boolean result = this.roleManager.save(roleStr,roleUsers);
			
	        if(result) {
	        	response.getWriter().write("{success:true}");
	        }else{
	        	response.getWriter().write("{failure:true}");
	        }
			
			transaction.commit();
		} catch (Exception e) {
			logger.error("", e);
			try {
				transaction.rollback();
			} catch (Exception e1) {
				logger.error("", e1);
				throw e;
			} finally {
				transaction = null;
				response.getWriter().write("{failure:true}");
			}
		}

		return null;
	}
	
	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
	
		String result = this.roleManager.GetRoles();
        logger.debug("roles:"+result);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (IOException e) {
			logger.error("输出json失败" ,e);
			return null;
		}
		return null;
	}
	
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		
		String id = request.getParameter("codes");
		
		Transaction transaction = null;

		response.setContentType("text/json;charset=utf-8");
		try {
			transaction = TransactionHelper.getTransaction();
			transaction.begin();

			boolean flag = this.roleManager.delete(id);

			if (flag == true) {
				response.getWriter().print("{success:true}");
			} else {
				response.getWriter().write("{failure:true}");
			}
			transaction.commit();
		} catch (Exception e) {
			try {
				transaction.rollback();
			} catch (Exception e1) {
				logger.error("", e);
				throw e;
			} finally {
				transaction = null;
				response.getWriter().write("{failure:true}");
			}
		}
		return null;
	}
	
	public ActionForward getUserTree(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String paraSeq =  request.getParameter("node");	
		int type = Integer.parseInt(request.getParameter("type") == null?"0":request.getParameter("type"));
		JSONArray jsonArray = this.roleManager.getUserTree(paraSeq,type);

		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(jsonArray);
		} catch (IOException e) {
			logger.error("输出json失败",e);
			return null;
		}
		return null;
	}
	
	public ActionForward getRoleTree(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JSONArray jsonArray = this.roleManager.getRoleTree();

		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(jsonArray);
		} catch (IOException e) {
			logger.error("输出json失败",e);
			return null;
		}
		return null;
	}
	
	/**
	 * 根据角色ID查找对应的用户或组ID
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward getUsersByRole (ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response)
	        throws Exception {
		//得到前台传来的id值查询相应的数据，并返回json格式的数据给前台
		String roleId = request.getParameter("roleId");

		UsersRolesManager um = new UsersRolesManager();
		String result = um.getUsersByRole(roleId);

		System.out.println("ID为:" + roleId + "的users为" + result);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (IOException e) {
			logger.error("输出ID为："+roleId+"的users失败" ,e);
			return null;
		}
		
		return null;
	}
		
}
